package com.example.xyxwebbackend001.util;


import com.example.xyxwebbackend001.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;

@Component
public class FileUploadUtil {
    private static FileUploadConfig fileUploadConfig;

    @Autowired
    public FileUploadUtil(FileUploadConfig config) {
        fileUploadConfig = config;
    }

    // 通用文件上传逻辑
    public static Map<String, Object> uploadFile(MultipartFile file, String token) throws IOException {
        String storageToken = (token != null && !token.isEmpty()) ? token : UUID.randomUUID().toString();
        Path uploadDir = Paths.get(fileUploadConfig.getUploadDir(), "temp", storageToken);
        Files.createDirectories(uploadDir);

        String fileName = String.format("%s_%s",
                UUID.randomUUID(),
                Paths.get(file.getOriginalFilename()).getFileName().toString());

        Files.write(uploadDir.resolve(fileName), file.getBytes());

        return Map.of(
                "url", String.format("/files/cult/temp/%s/%s", storageToken, fileName),
                "articleToken", storageToken
        );
    }

    // 通用文件删除逻辑
    public static boolean deleteFile(String fileName, String articleToken) throws IOException {
        Path filePath = Paths.get(fileUploadConfig.getUploadDir(), "temp", articleToken, fileName).normalize();

        Path validPath = Paths.get(fileUploadConfig.getUploadDir(), "temp").normalize();
        if (!filePath.startsWith(validPath)) {
            return false;
        }

        if (Files.exists(filePath)) {
            Files.delete(filePath);
            Path parentDir = filePath.getParent();
            if (Files.isDirectory(parentDir) && Files.list(parentDir).count() == 0) {
                Files.delete(parentDir);
            }
            return true;
        }
        return false;
    }

    // 通用文件迁移逻辑
    public static void migrateTempFiles(String articleToken, String targetPath) throws IOException {
        Path sourceDir = Paths.get(fileUploadConfig.getUploadDir(), "temp", articleToken);
        Path targetDir = Paths.get(fileUploadConfig.getUploadRecDir(), targetPath);

        if (Files.exists(sourceDir)) {
            Files.createDirectories(targetDir);
            try (Stream<Path> files = Files.list(sourceDir)) {
                files.forEach(source -> {
                    try {
                        String[] nameParts = source.getFileName().toString().split("_", 2);
                        String originalName = nameParts.length > 1 ? nameParts[1] : nameParts[0];
                        Files.move(source, targetDir.resolve(originalName), StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e) {
                        throw new RuntimeException("文件迁移失败: " + e.getMessage(), e);
                    }
                });
            }
            Files.deleteIfExists(sourceDir);
        }
    }
}
